using SX.BaseService.Repository.Core;
using SX.BaseService.Repository.Entity;
using SX.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SX.BaseService.Service
{
    /// <summary>
	/// SysRolePermission服务层
	/// </summary>
    public class SysRolePermissionService: DbContext,ISysRolePermissionService
    {
        public SysRolePermissionService()
        {
          
        }

        public async Task<IApiResult> Add(List<string> list, string roleId)
        {
            //删除出当前角色所有的权限
            Db.BeginTran();
            await Db.Deleteable<SysRolePermissionEntity>().Where(x => x.RoleId == roleId).ExecuteCommandAsync();
            List<SysRolePermissionEntity> list_add = new List<SysRolePermissionEntity>();
            foreach(var item in list)
            {
                var data = new SysRolePermissionEntity();
                data.RoleId = roleId;
                data.PermissionId = item;
                list_add.Add(data);
            }
            //批量插入
            var res= await Db.Insertable(list_add).ExecuteCommandAsync();
            if (res <= 0)
            {
                Db.RollbackTran();
            }
            Db.CommitTran();
            return ApiResult.Ok();
        }

        public async Task<IApiResult> GetPermissionList()
        {
            var permissions = await Db.Queryable<SysPermissionEntity>().ToListAsync();
               
            var apis = permissions
                .Where(a => a.Type ==1)
                .Select(a => new { a.Id, a.ParentId, a.Name });

            var sql = @"select distinct  sp.Id,sp.Name,sp.Code,sp.Path,sp.Icon,sp.Sort,sp.CreateTime,sp.Remarks,sp.ParentId from SysPermission sp 
            left join SysRolePermission srp on sp.Id=srp.PermissionId 
            left join SysUserRole sur on sur.SysRoleId=srp.RoleId  where sp.Type=0 and sp.Enabled=1 order by sort asc";
           
            var Allmenus = await Db.Ado.SqlQueryAsync<SysPermissionEntity>(sql);

            var menus=Allmenus                       
                .Select(a => new
                {
                    a.Id,
                    a.ParentId,
                    Label= a.Name,
                    Apis = apis.Where(b => b.ParentId == a.Id).Select(b => new { b.Id, b.Name }),
                });
            var appApis = apis.Select(c => new { c.Id,Label=c.Name }).FirstOrDefault();//TODO
            return ApiResult.Ok(new {menus=menus,appapis=appApis });
        }

        public IApiResult QueryPermission(string roleId)
        {
            var list_permission = Db.Queryable<SysRolePermissionEntity>().Where(x => x.RoleId == roleId).Select(x=>x.PermissionId).ToList();

            return ApiResult.Ok(list_permission);
           
        }
    }
}